<?php

  require("../setup.inc.php");
//  require_once('sessions.inc.php');
  //session_start();

if(isset($_REQUEST['saveShift'])) {
	//error checking.. lets see if they broke any rules, and somehow got around the javascript.
	$manager_override = 0;
	if(checkQualified(1000)) {
		$manager_override = $_REQUEST['man_override'];
	}

	if(isset($_REQUEST['driver_id']) and (checkQualified(1000) or isDispatcher())) {
		//driver id is set by am to assign a shift to someone else
		$assigneeid = $_REQUEST['driver_id'];
	} else {
		//driver id is set by session variable
		$assigneeid = $_SESSION['driver_id'];
	}
	//initialize error array
	$errors = array();
	
	if(ENFORCE_2HOUR_LINE and !$manager_override) {
		// Check to see if there is 0 minutes or > 2 hours between start time and last shift end time
		$check1 = mysql_query("SELECT * FROM `t_sched_shifts` WHERE `structure_id` = " . $_REQUEST['sid'] . " AND `shift_end` <= " . $_REQUEST['startTime'] . " ORDER BY `shift_end` DESC LIMIT 1");
		if(mysql_num_rows($check1) == 1) {
			$priorShift = mysql_fetch_assoc($check1);
			if( ( $priorShift['shift_end'] == $_REQUEST['startTime'] ) or ( $priorShift['shift_end'] <=  $_REQUEST['startTime'] - 200 ) ) {
				//good!
			} else {
				$this_error = array('err_no'    => "S01",
									'err_title' => "No 2 hour gap (Line)",
									'err_text'  => "You must start your shift right after the previous shift, or leave at least a two hour gap!");
				array_unshift($errors,$this_error);
				$error .= "\n<div>You must start your shift right after the previous shift, or leave at least a two hour gap! (Error # S01)</div>";
			}
		} else {
			$check1a = mysql_query("SELECT * FROM `t_sched_structure` WHERE `structure_id` =  " . $_REQUEST['sid']);
			$lineStart = mysql_fetch_assoc($check1a);
			if ( ( $lineStart['start'] == $_REQUEST['startTime'] ) or ( $lineStart['start'] <= $_REQUEST['startTime'] - 200 ) ) {
				//good!
			} else {
				$this_error = array('err_no'    => "S02",
									'err_title' => "No 2 hour gap (Line)",
									'err_text'  => "You must start your shift at the beginning of this line, or leave at least a two hour gap!");
				array_unshift($errors,$this_error);
				$error .= "\n<div>You must start your shift at the beginning of this line, or leave at least a two hour gap! (Error # S02)</div>";
			}
			mysql_free_result($check1a);
		}
		mysql_free_result($check1);
	}
	if(ENFORCE_2HOUR_SHIFT and !$manager_override) {
		//
		// Check to see if there is 0 minutes or > 2 hours between end time and next shift start
		//
		$check2 = mysql_query("SELECT * FROM `t_sched_shifts` WHERE `structure_id` = " . $_REQUEST['sid'] . " AND `shift_start` >= " . $_REQUEST['endTime'] . " ORDER BY `shift_start` ASC LIMIT 1");
		if(mysql_num_rows($check2) == 1) {
			$nextShift = mysql_fetch_assoc($check2);
			if( ( $nextShift['shift_start'] == $_REQUEST['endTime'] ) or ( $nextShift['shift_start'] >=  $_REQUEST['endTime'] + 200 ) ) {
				//good!
			} else {
				$this_error = array('err_no'    => "S03",
									'err_title' => "No 2 hour gap (Shift)",
									'err_text'  => "You must end your shift right before the next shift, or leave at least a two hour gap!");
				array_unshift($errors,$this_error);
				$error .= "\n<div>You must end your shift right before the next shift, or leave at least a two hour gap! (Error # S03)</div>";
			}
		} else {
			$check2a = mysql_query("SELECT * FROM `t_sched_structure` WHERE `structure_id` =  " . $_REQUEST['sid']);
			$lineStart = mysql_fetch_assoc($check2a);
			if ( ( $lineStart['end'] == $_REQUEST['endTime'] ) or ( $lineStart['end'] >= $_REQUEST['endTime'] + 200 ) ) {
				//good!
			} else {
				$this_error = array('err_no'    => "S04",
									'err_title' => "No 2 hour gap (Shift)",
									'err_text'  => "You must end your shift at the end of this line, or leave at least a two hour gap!");
				array_unshift($errors,$this_error);
				$error .= "\n<div>You must end your shift at the end of this line, or leave at least a two hour gap! (Error # S04)</div>";
			}
			mysql_free_result($check2a);
		}
		mysql_free_result($check2);
		if(subtractTime($_REQUEST['endTime'],$_REQUEST['startTime']) > 430) {
			$this_error = array('err_no'    => "S05",
								'err_title' => "4 Hour Shift Limit",
								'err_text'  => "Your shift is longer than 4 hours." );
			array_unshift($errors,$this_error);
			$error .= "\n<div>Shift longer than 4 hours. (Error # S05)</div>";
		}
	} //end enforce rules if
	//
	if(ENFORCE_LOGIC) {
		// Check to see if start time = end time
		if( $_REQUEST['endTime'] <= $_REQUEST['startTime'] ) {
			$this_error = array('err_no'    => "S06",
								'err_title' => "Logical Error",
								'err_text'  => "Your end time must be greater than your start time." );
			array_unshift($errors,$this_error);
			$error .= "\n<div>End time must be greater than start time. (Error # S06)</div>";
		}
	}

	//get table_id
	$grabTableID = mysql_query("SELECT * FROM `t_sched_structure` WHERE `structure_id` = " . $_REQUEST['sid']);		
	$structure_data = mysql_fetch_assoc($grabTableID);
	
	if(ENFORCE_OVERLAP and !$manager_override) {
		//check to see if this shift will overlap any other shift
		//is this a training shift??
		$sql = sprintf("SELECT `line` FROM `t_sched_structure`
						WHERE `structure_id` = %s
						LIMIT 1",
							quote_smart($_REQUEST['sid']));
		$result = mysql_query($sql);
		if(mysql_num_rows($result) != 1)
			$this_error = array('err_no'    => "S11",
								'err_title' => "System Error",
								'err_text'  => "Couldn't find the shift for buswash analysis." );
			array_unshift($errors,$this_error);
			$error .= "\n<div>Couldn't find the shift for buswash analysis. (Error # S11)</div>";
		$row = mysql_fetch_assoc($result);
		if ($row['line'] == 'T') {
			//this is a training shift.. change the SQL code to remove training shifts.. TEMPORARY FIX!!
			$sql = sprintf("SELECT `t_sched_shifts`.* FROM `t_sched_shifts`,`t_sched_structure`
							WHERE `t_sched_shifts`.`driver_id` = %s 
							  AND `t_sched_shifts`.`structure_id` = `t_sched_structure`.`structure_id`
							  AND `t_sched_structure`.`line` <> 'T'
							  AND `t_sched_structure`.`table_id` = %s 
							  AND ( (`t_sched_shifts`.`shift_end` > %s AND `t_sched_shifts`.`shift_end` < %s )
								 OR (`t_sched_shifts`.`shift_end` > %s AND `t_sched_shifts`.`shift_start` < %s ) 
								 OR (`t_sched_shifts`.`shift_start` > %s AND `t_sched_shifts`.`shift_start` < %s )
								 )",

								quote_smart($assigneeid),
								quote_smart($structure_data['table_id']),
								quote_smart(subtractTime($_REQUEST['startTime'],9)),
								quote_smart(addTime($_REQUEST['endTime'],9)),
								quote_smart(sprintf("%04d",$_REQUEST['endTime'])),
								quote_smart(sprintf("%04d",$_REQUEST['startTime'])),
								quote_smart(sprintf("%04d",$_REQUEST['startTime'])),
								quote_smart(sprintf("%04d",$_REQUEST['endTime'])));
		} else {
			//it's not a training shift.. default SQL will do
			$sql = sprintf("SELECT `t_sched_shifts`.* FROM `t_sched_shifts`,`t_sched_structure`
							WHERE `t_sched_shifts`.`driver_id` = %s 
							  AND `t_sched_shifts`.`structure_id` = `t_sched_structure`.`structure_id`
							  AND `t_sched_structure`.`table_id` = %s 
							  AND ( (`t_sched_shifts`.`shift_end` > %s AND `t_sched_shifts`.`shift_end` < %s )
								 OR (`t_sched_shifts`.`shift_end` > %s AND `t_sched_shifts`.`shift_start` < %s ) 
								 OR (`t_sched_shifts`.`shift_start` > %s AND `t_sched_shifts`.`shift_start` < %s )
								 )",

								quote_smart($assigneeid),
								quote_smart($structure_data['table_id']),
								quote_smart(subtractTime($_REQUEST['startTime'],9)),
								quote_smart(addTime($_REQUEST['endTime'],9)),
								quote_smart(sprintf("%04d",$_REQUEST['endTime'])),
								quote_smart(sprintf("%04d",$_REQUEST['startTime'])),
								quote_smart(sprintf("%04d",$_REQUEST['startTime'])),
								quote_smart(sprintf("%04d",$_REQUEST['endTime'])));
		}
		//this sql is long!!
		
		$overlap_result = mysql_query($sql);
		if(mysql_num_rows($overlap_result)) {
			$this_error = array('err_no'    => "S07",
								'err_title' => "Concurrent Shifts",
								'err_text'  => "The shift you are trying to take overlaps a previously assigned shift." );
			array_unshift($errors,$this_error);
			$error .= "\n<div>Overlapping shift! (Error # S07)</div>";
		}
	}

	if(ENFORCE_PERMISSIONS and !$manager_override) {
		//check permissions of the shift they are trying to take, and their permissions
		$sql = "SELECT `permission` FROM `t_drivers` WHERE `driver_id` = $assigneeid";
		$perm_result = mysql_query($sql);
		$row_data = mysql_fetch_assoc($perm_result);
		$person_to_check = $row_data['permission'];
		if(!checkQualified($structure_data['permissions'],$person_to_check)) {
			$this_error = array('err_no'    => "S08",
								'err_title' => "Not Qualified",
								'err_text'  => "You are not qualified for this shift! " );
			array_unshift($errors,$this_error);
			$error .= "\n<div>You are not allowed to sign up for this shift! (Error # S08)</div>";
		}
		mysql_free_result($perm_result);
	}
	if(ENFORCE_SIGNUP_TIME and !$manager_override) {
		//enforces the signup time slots
		$sql = "SELECT `signup_id`
					FROM `t_sched_signups` , `t_sched_structure` , `t_sched_main` , `t_sched_groups`
					WHERE `t_sched_signups`.`driver_id` = $assigneeid
					AND `t_sched_structure`.`structure_id` = " . $_REQUEST['sid'] . "
					AND `t_sched_structure`.`table_id` = `t_sched_main`.`table_id`
					AND `t_sched_main`.`group_id` = `t_sched_signups`.`group_id`
					LIMIT 1";
		$signup_result = @mysql_query($sql);
		if(@mysql_num_rows($signup_result) < 1)
			$this_error = array('err_no'    => "S09",
								'err_title' => "No Signup Time",
								'err_text'  => "You do not have a signup time." );
			array_unshift($errors,$this_error);
			$error .= "\n<div>You do not have a signup time. (Error # S09A)</div>";
		$signup_data = @mysql_fetch_assoc($signup_result);
		if(!signupTime($signup_data['signup_id'],$assigneeid) and (@mysql_num_rows($signup_result) > 0)) {
			$this_error = array('err_no'    => "S10",
								'err_title' => "Future Signup Time",
								'err_text'  => "Your signup time is in the future." );
			array_unshift($errors,$this_error);
			$error .= "\n<div>Your signup time is in the future. (Error # S10)</div>";
		}
		@mysql_free_result($signup_result);
	}
	
	if(ENFORCE_NO_SIGNUPS_WHILE_PENDING and !$manager_override and !isDispatcher()) {
		//makes sure they can't signup during a pending schedule
		$sql = "SELECT `t_sched_groups`.`status`
					FROM `t_sched_structure` , `t_sched_main` , `t_sched_groups`
					WHERE `t_sched_structure`.`structure_id` = " . $_REQUEST['sid'] . "
					AND `t_sched_structure`.`table_id` = `t_sched_main`.`table_id`
					AND `t_sched_main`.`group_id` = `t_sched_groups`.`group_id`
					AND `t_sched_groups`.`status` = 1
					LIMIT 1";
		$no_pending_result = mysql_query($sql);
		if(@mysql_num_rows($no_pending_result) == 1) {
			$this_error = array('err_no'    => "S14",
								'err_title' => "Read-only While Pending",
								'err_text'  => "You cannot take shifts while a schedule is in Pending mode. Call base if you would like this shift." );
			array_unshift($errors,$this_error);
			$error .= "\n<div>You cannot take shifts while a schedule is in Pending mode. (Error # S14)</div>";
		}
		@mysql_free_result($no_pending_result);
	}
	
	if(ENFORCE_40_HOUR_LIMIT and !$manager_override) {
		//make sure they haven't gone over 40 hours
		
		//find out what week this shift is a part of
		$sql = sprintf("	SELECT `t_sched_main`.`week`,`t_sched_main`.`group_id` 
							FROM `t_sched_main`,`t_sched_structure`
							WHERE `t_sched_main`.`table_id` = `t_sched_structure`.`table_id`
							  AND `t_sched_structure`.`structure_id` = %s",
						quote_smart($_REQUEST['sid']));
		$weekResult = mysql_query($sql);
		$weekRow = mysql_fetch_assoc($weekResult);
		$week = $weekRow['week'];
		$groupId = $weekRow['group_id'];
		mysql_free_result($weekResult);
		
		//Add up all shifts from this week
		$sql = sprintf("	SELECT `t_sched_shifts` . *
							FROM `t_sched_main` , `t_sched_structure` , `t_sched_shifts`
							WHERE `t_sched_main`.`week` = %s
							AND `t_sched_main`.`group_id` = %s
							AND `t_sched_main`.`table_id` = `t_sched_structure`.`table_id`
							AND `t_sched_structure`.`structure_id` = `t_sched_shifts`.`structure_id`
							AND `t_sched_shifts`.`driver_id` = %s",
						quote_smart($week),
						quote_smart($groupId),
						quote_smart($assigneeid));
		$allShiftsResult = mysql_query($sql);
		$hours = 0;
		if(mysql_num_rows($allShiftsResult) > 0) {
			while($row = mysql_fetch_assoc($allShiftsResult)) {
				$moreHours = paylogTime($row['shift_end']) - paylogTime(subtractTime($row['shift_start'],0010));
				$hours = $moreHours + $hours;
			}
		}

		//add in the current shift
		$moreHours = paylogTime($_REQUEST['endTime']) - paylogTime(subtractTime($_REQUEST['startTime'],0010));
		$hours = $moreHours + $hours;
		
		//check if it's over 40
		if($hours > 40) {
			$amountOver = $hours - 40;
			$this_error = array('err_no'    => "S15",
								'err_title' => "No Overtime",
								'err_text'  => "This shift would put you into overtime by " . $amountOver . "!" );
			array_unshift($errors,$this_error);
			$error .= "\n<div>This shift would put you into overtime by " . $amountOver . "! (Error # S10)</div>";
		}
	}

	//verify that they are only a driver if they want to take buswash
	if(ENFORCE_BUSWASH_RESTRICTION and !$manager_override) {
		//check if this shift is in fact bus wash
		$sql = sprintf("SELECT `line` FROM `t_sched_structure`
						WHERE `structure_id` = %s
						LIMIT 1",
							quote_smart($_REQUEST['sid']));
		$result = mysql_query($sql);
		if(mysql_num_rows($result) != 1)
			$this_error = array('err_no'    => "S11",
								'err_title' => "System Error",
								'err_text'  => "Couldn't find the shift for buswash analysis." );
			array_unshift($errors,$this_error);
			$error .= "\n<div>Couldn't find the shift for buswash analysis. (Error # S11)</div>";
		$row = mysql_fetch_assoc($result);
		if ($row['line'] == 'BW') {
			//this is a bus wash shift.. check if they are too high up to take it
			$overQualified = false;
			if(checkQualified(0100) or checkQualified(0200) or checkQualified(0400))
				$overQualified = true;
			if($overQualified) {
				$this_error = array('err_no'    => "S12",
									'err_title' => "Overqualified",
									'err_text'  => "You are overqualified for buswash." );
				array_unshift($errors,$this_error);
				$error .= "\n<div>You are overqualified for buswash. (Error # S12)</div>";
			}
		}
	}

	//verify that the schedule is not locked.. if it is, check if its locked to them
	if(ENFORCE_EXCLUSION and !$manager_override) {
		//get the group id
		$result = mysql_query("SELECT `group_id` FROM `t_sched_main` WHERE `table_id` = " . $structure_data['table_id']);
		$tabledata = mysql_fetch_assoc($result);
		if(exclusionActiveGroup($tabledata['group_id']) && (exclusionActiveGroup($tabledata['group_id']) != $assigneeid)) {
			$this_error = array('err_no'    => "S13",
								'err_title' => "Exclusive Access",
								'err_text'  => driverName(exclusionActiveGroup($tabledata['group_id'])) . " has exclusive access!" );
			array_unshift($errors,$this_error);
			$error .= "\n<div>" . driverName(exclusionActiveGroup($tabledata['group_id'])) . " has exclusive access! (Error # S13)</div>";
		}
	}

	
	//
	// Assuming all is good, assign the shift.. (ooh... so exciting!)
	//

	//clean up the error array
	$clean_errors = array();
	foreach($errors as $inspect) {
		if(!empty($inspect)) array_unshift($clean_errors,$inspect);
	}
	//replace the old error array
	$errors = $clean_errors;

//	if(!isset($error)) {
	if(count($errors) == 0) {
		$assignSQL = "INSERT INTO `t_sched_shifts` (table_id,driver_id,structure_id,shift_start,shift_end) VALUES (" . $structure_data['table_id'] . "," . $assigneeid . "," . $_REQUEST['sid'] . ",'" . sprintf("%04d",$_REQUEST['startTime']) . "','" . sprintf("%04d",$_REQUEST['endTime']) . "')";
		$assign = mysql_query($assignSQL);
		if(mysql_affected_rows() != 1) {
			$error_msg = "MySQL error: " . mysql_error() . " ( " . mysql_errno() . " )";
		} else {
			
			$closeText = "self.close();";
		}
		?>
			<script language="javascript">
				<!-- hide
				window.opener.location.reload();
				//alert("<?= $assignSQL ?>");
				<?= $closeText ?>
				//-->
			</script>
			<?php print_r($_REQUEST); ?>
		<?php
	} else {
		?>
		<html>
		<head>
		</head>
		<body style="margin:0px; ">

<?php if($assigneeid != $_SESSION['driver_id']) { ?>
			<div id="coordinatorToolbar" style="background-color:#FFFFCC; border-bottom: 1px solid black; margin:0px; padding: 5px; text-align:center; font-family:Verdana, Arial, Helvetica, sans-serif; font-size: 12px; font-weight:bold; ">Acting as <?= driverName($assigneeid) ?></div>
<?php } ?>

<div style="width:100%; margin: 0px 0px 0px 0px; padding:5px; background-color:#B0B0FF; border-bottom: 1px solid black; font-family:Verdana,Tahoma; font-weight:700; font-size:12px;">The system could not assign the shift because it experienced the following errors:</div>
<!--
<?php print_r($errors); ?>
-->

<?php	foreach($errors as $current_error) { 
			if(($last_error == $current_error['err_no']) or ($current_error['err_no'] == '')) 
				continue;
			$last_error = $current_error['err_no'];

?>
<div style="width:100%; margin: 0px 0px 0px 0px; border-bottom:1px solid black; padding:3px; ">
	<span style="font-family:Verdana,Tahoma; font-weight:bold; color: red; font-size:12px; display:block; "><?= $current_error['err_no'] ?>: <?= $current_error['err_title'] ?></span>
	<span id="error1_detail" style="font-family:Verdana,Tahoma; display:block; font-size:10px; padding-left:10px;"><?= $current_error['err_text'] ?></span>
</div>
<?php 	} ?>

<div style="text-align: center; margin:10px;"><input type="button" value="Go Back" onClick="history.go(-1)"> <input type="button" value="Cancel" onClick="self.close()"></div>

<?php if(checkQualified(1000)) { //if above am, allow assigning others and breaking rules?>
			<div style="text-align: center;">
				<form action="<?= $_SERVER['PHP_SELF'] ?>" method="post">
					<input type="hidden" name="startTime" value="<?= $_REQUEST['startTime'] ?>">
					<input type="hidden" name="endTime" value="<?= $_REQUEST['endTime'] ?>">
					<input type="hidden" name="saveShift" value="<?= $_REQUEST['saveShift'] ?>">
					<input type="hidden" name="sid" value="<?= $_REQUEST['sid'] ?>">
					<input type="hidden" name="driver_id" value="<?= $_REQUEST['driver_id'] ?>">
					<input type="hidden" name="man_override" value="1">
					<input style="background-color:#FF0000; font-weight:bold; font-family:Verdana,Tahoma;" type="submit" value="Override Rules" > 
				</form></div>
			
<?php } // end if ?>
		</body></html>

<?php
	}
	exit;
}

  $query = mysql_query(sprintf("SELECT `t_sched_structure` . * , `t_sched_main`.`description` AS day_description, `t_sched_groups`.`description` AS group_description, `t_sched_groups`.`status`
						FROM t_sched_structure, t_sched_main, t_sched_groups
						WHERE t_sched_structure.table_id = t_sched_main.table_id
						AND t_sched_groups.group_id = t_sched_main.group_id
						AND t_sched_structure.structure_id = %s",
							quote_smart($_REQUEST['sid'])));
  $shift = mysql_fetch_assoc($query);

  

?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title><?= $shift['description'] ?></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

<script language="JavaScript" type="text/JavaScript">
function checkShift () {
	//startTime, endTime, line, day, schedGroup
	errors          = false;
	startTime       = document.myform.startTime.options[document.myform.startTime.selectedIndex].text;
	endTime         = document.myform.endTime.options[document.myform.endTime.selectedIndex].text;
	previousEndTime = <?= $_GET['pet'] ?>;
	nextStartTime   = <?= $_GET['nst'] ?>;
	shiftID         = <?= $_GET['sid'] ?>;
<?php 
/* don't process this section
	//check to see if there is 0 minutes or > 2 hours between start time and last shift
	if (!(startTime == previousEndTime) && ( previousEndTime > (startTime - 200))) {
		errors = true;
		alert("You must start your shift immediately after the previous shift, or leave a minimum of a two hour gap between shifts! (Error # C01)");
	}
	//check to see if there is 0 minutes or > 2 hours between end time and next shift start
	if (!(endTime == nextStartTime) && (endTime > (nextStartTime - 200))) {
		errors = true;
		alert("You must end your shift immediately before the next shift, or leave a minimum of a two hour gap between shifts! (Error # C02)");
	}
	//check to see if start time = end time
	if(startTime == endTime) {
		errors = true;
		alert("Your start and end times must be different! (st: " + startTime + "; et: " + endTime + ") (Error # C03)");
	}
	//check to verify that the start time is in fact before the end time??
	if(endTime < startTime) {
		errors = true;
		alert("Your start time must take place before your end time! (Error # C04)");
	}
*/ ?>
	//confirm that they want the shift, and remind them that it is permanent
	if(!errors) { //check if there were errors
		if(confirm("Remember:\n\tBy continuing, you are taking this shift permanently for this\n\tschedule. Any changes from here on will require an\n\tAssistant Manager's approval.")) {
			return true; 
		} else {
			return false;
		}
	} else {
		alert("Fix the errors and try submitting again.");
	}
	return false;

}

</script>
<link href="http://transpo.uconn.edu/css/global.css" rel="stylesheet" type="text/css">
</head>
<body bgcolor="#000066" onLoad="self.focus()">
<form name="myform" id="myform" onSubmit="return checkShift()" method="post" action="<?= $_SERVER['PHP_SELF'] ?>">
<div align="center" style="padding-top: 4px;">
<table width="250" style="border: 2px solid white; background-color: #CCCCCC">
  <tr> 
    <td colspan="2"><div align="center" style="padding: 2px;"> 
        <div><?= $shift['description'] ?></div>
		<div>on <?= $shift['day_description'] ?></div>
		<div>of the <?= $shift['group_description'] ?></div>
      </div></td>
  </tr>
  <tr> 
    <td style="border: 2px solid black; "> <div align="center">Shift Start</div>
      <div align="center" style="padding: 2px;"> 
        <select name="startTime">
		<option SELECTED value="<?= padOutputTime($_REQUEST['pet']) ?>"><?= formatOutputTime($_REQUEST['pet']) ?></option>
<?php
	$firstDriverChangeTime = addTime($shift['start'],'0200');
	$queryStartSql = "SELECT `t_sched_dc_times`.dc_time FROM `t_sched_dc_times` WHERE t_sched_dc_times.dc_group_id = " . $shift['dc_group_id'] . "  AND t_sched_dc_times.dc_time > " . $_REQUEST['pet'] . " AND t_sched_dc_times.dc_time < " . $_REQUEST['nst'] . " AND t_sched_dc_times.dc_time >= $firstDriverChangeTime ORDER BY dc_time ASC";
	print "<!-- $queryStartSql --> \n";
	$queryStart = mysql_query($queryStartSql);
	
	while($row = mysql_fetch_assoc($queryStart)) {
		?>
          <option value="<?= padOutputTime($row['dc_time']) ?>"><?= formatOutputTime($row['dc_time']) ?></option>
		<?php
	}
	mysql_free_result($queryStart);
?>
        </select>
      </div></td>
    <td style="border: 2px solid black; "> <div align="center">Shift End</div>
      <div align="center" style="padding: 2px;"> 
        <select name="endTime">
<?php
	$lastDriverChangeTime = subtractTime($shift['end'],'0200');
	$queryStart = mysql_query("SELECT `t_sched_dc_times`.dc_time FROM `t_sched_dc_times`  WHERE t_sched_dc_times.dc_group_id = " . $shift['dc_group_id'] . " AND t_sched_dc_times.dc_time > " . $_REQUEST['pet'] . " AND t_sched_dc_times.dc_time < " . $_REQUEST['nst'] . " AND t_sched_dc_times.dc_time <= $lastDriverChangeTime ORDER BY dc_time ASC");
	print "<!-- SELECT `t_sched_dc_times`.dc_time FROM `t_sched_dc_times`  WHERE t_sched_dc_times.dc_group_id = " . $shift['dc_group_id'] . " AND t_sched_dc_times.dc_time > " . $_REQUEST['pet'] . " AND t_sched_dc_times.dc_time < " . $_REQUEST['nst'] . " AND t_sched_dc_times.dc_time <= $lastDriverChangeTime ORDER BY dc_time ASC -->\n";
	while($row = mysql_fetch_assoc($queryStart)) {
		?>
          <option value="<?= padOutputTime($row['dc_time']) ?>"><?= formatOutputTime($row['dc_time']) ?></option>
		<?php
	}
	mysql_free_result($queryStart);
?>
		<option SELECTED value="<?= padOutputTime($_REQUEST['nst']) ?>"><?= formatOutputTime($_REQUEST['nst']) ?></option>
        </select>
      </div></td>
  </tr>
  <tr> 
    <td colspan="2">
		<div align="center" style="padding: 3px;">
		<input type="hidden" name="saveShift" value="1">
		<input type="hidden" name="sid" value="<?= $_GET['sid'] ?>">
        <input type="submit" name="takeShift" value="Take Shift" >&nbsp;&nbsp;
        <input type="button" name="cancel" onClick="self.close()" value="Cancel">
      </div>
    </td>
  </tr>
<?php if(checkQualified(1000) or isDispatcher()) { //if above am, allow assigning others and breaking rules?>
  <tr>
    <td colspan="2">
		<div align="center" style="padding: 3px;">

  <select name="driver_id">
    <option value="<?=$_SESSION['driver_id']?>" selected> - Assign to Someone Else - </option>
	<?php
		$driver_sql = "SELECT `driver_id` , concat( `lastname` , \", \", `firstname` ) AS name FROM t_drivers WHERE `terminated` IS NULL ORDER BY `lastname` ASC, `firstname` ASC";
		$driver = mysql_query($driver_sql);
		while($driver_data = mysql_fetch_assoc($driver)) {
			print "    <option value=\"" . $driver_data['driver_id'] . "\">" . $driver_data['name'] . "</option>\n";
		}
		mysql_free_result($driver);
	?>
  </select> 
      </div>
    </td>
  </tr>
<?php } //end if ?>

</table>
</div>
</form>
</body>
</html>